<template>
	<view class="uni-tab-bar">
		<view class="user-info">
			<view class="base-info">
				<image :src="user.avatarLarge || '../../static/img/common/avatar.png'" class="avatar"></image>
				<view class="username">{{user.username}}</view>
				<view class="sign">{{user.selfDescription}}</view>
			</view>
			<view class="other-info">
				<view v-if="user.jobTitle">
					<i class="my-icon iconfont iconpeople"></i>
					<text>{{user.jobTitle}}</text>
				</view>
				<view v-if="user.company">
					<i class="my-icon iconfont iconhomepage"></i>
					<text>{{user.company}}</text>
				</view>
				<view v-if="user.blogAddress">
					<i class="my-icon iconfont iconcoordinates"></i>
					<text>{{user.blogAddress}}</text>
				</view>
			</view>
			
			<view class="dashed"></view>
			<view class="tags">
				<view class="tagTitle">标签</view>
				<view v-for="(tag, index) in user.tags" v-bind:key="tag" wx:key="tags" class="tag">{{tag.title}}</view>
			</view>
			<view class="dashed"></view>
			<view class="categories">
				<view class="catTitle">分类</view>
				<view class="container">
					<view class="row" v-for="(cat, index) in user.categories" v-bind:key="cat" wx:for="cat">
						<image class="ico" :src="cat.icon"></image>
						<text class="cat">{{cat.name}}</text>
					</view>
				</view>
			</view>
			<view class="dashed"></view>
		</view>
		<view class="list">
			<view class="postListTitle">TA的文章</view>
			<block v-for="(newsItem, newsIndex) in currentList" v-bind:key="newsIndex" :id="newsItem.id">
				<view class="feed-list-item" hover-class="item-hover" @click="goDetail(newsItem)">
					<view class="feed-list-item-title-avatar">
						<image class="image avatar" :class="{lazy:!newsItem.show}" :data-index="newsIndex" @load="imgOnLoad" :src="newsItem.show?newsItem.avatar:''" />
						<image class="image avatar placeholder" :class="{loaded:newsItem.loaded}" src="../../static/img/common/avatar.png" />
					</view>
					<view class="feed-list-item-text-area">
						<text class="feed-list-item-title">{{newsItem.title}}</text>
						<text class="feed-list-item-summaryInfo">{{newsItem.summaryInfo}}</text>
					</view>
					<view class="feed-list-item-date-author-area">
						<view class="feed-list-item-sm-text">{{newsItem.postdate}} @{{newsItem.author}}</view>
					</view> 
				</view>
			</block>
			<view v-if="showLoading" class="feed-list-item" hover-class="item-hover" style="margin-bottom: 120upx;">
				<view class="feed-list-item-title-area">
					<text class="align-center-vertical" style="width: 100%;text-align: center;line-height: 120upx;">正在加载数据，请稍后...</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import service from '../../common/service.js';
	
	let utils = require("@/common/util.js")
	
	export default {
		data() {
			return {
				showLoading: true,
				scrollLeft: 0,
				refreshing: false,
				refreshText: '下拉可以刷新',
				newsList: [],
				currentList: [],
				tabIndex: 'all',
				categories_key:'junjin_categories',
				tabBars: [],
				windowHeight: 0,
				uid: '',
				user: {},
				requestParams: {size: 10, channel: 'weapp'}
			}
		},
		onLoad: function(options) {
			this.windowHeight = uni.getSystemInfoSync().windowHeight;
			this.uid = options.uid || '5589432fe4b0416bdfc8fe60';
			// 初始化列表信息
			this.tabBars.forEach((tabBar) => {
				this.newsList.push({'all':{
					data: [],
					requestParams: {
						columnId: tabBar.id,
						size: 10,
						channel: 'weapp',
					},
				}});
			});
			this.getUser();
			this.getCategoryList();
			this.getList();
		},
		onPullDownRefresh(event){
			this.refreshText = '正在刷新...';
			this.refreshing = true;
			this.getList();
		},
		onReachBottom(event){
			this.getList(2);
		},
		onPageScroll() {
			this.loadImg();
		},
		onShareAppMessage() {
			return {
				title: this.user.username,
				path: '/pages/list/user?uid=' + this.uid
			}
		},
		methods: {
			getCategoryList() {
				var that = this;
				that.tabBars = [{
					id: 'all',
					name: '全部',
					title: 'all',
					icon: ''
				}];
			},
			getUser(){
				var that = this;
				uni.request({
					url:'https://bukaa.cn/api-cms/juejin/user/' + that.uid,
					success(result) {
						var data = result.data;
						if (data.status === 'ok') {
							that.user = data.data;
						}
					}
				})
			},
			getList(action = 1) {
				var that = this;
				if (action === 1) {
					that.requestParams.page = 1;
				}
				that.showLoading = true;
				uni.request({
					url: 'https://bukaa.cn/api-cms/juejin/findByUser/' + that.uid,
					data: that.requestParams,
					success: (result) => {
						var data = result.data;
						if (data.status === 'ok') {
							var feeds = data.data.list;
							if (feeds && feeds.length > 0) { // 如果有返回数据
								const data = feeds.map((news) => {
									return {
										id: news.id,
										article_type: 1,
										title: news.title,
										postdate: utils.getDateDiff(utils.formatTime(new Date(news.updatedAt))),
										title: news.title,
										avatar: JSON.parse(news['user'])['avatarLarge'] || 'http://io.bukaa.cn/touxiang-girl.png',
										author: JSON.parse(news['user'])['username'],
										comment_count: news.commentsCount,
										post_id: news.id,
										summaryInfo: news.summaryInfo,
										show: false,
										loaded: false
									};
								});
								if (action === 1) {
									that.data = data;
									that.refreshing = false;
									setTimeout(() => {
										that.loadImg();
									}, 100)
								} else {
									data.forEach((news) => {
										that.data.push(news);
									});
								}
								that.currentList = that.data;
							} else {
								//self.setData({ loading: false });
							}
							that.requestParams.page += 1;
						}
					},
					complete:()=>{
						that.showLoading = false;
						uni.stopPullDownRefresh();
					}
				});
			},
			goDetail(detail) {
				uni.navigateTo({
					url: './detail?query=' + encodeURIComponent(JSON.stringify(detail))
				});
			},
			loadMore() {
				this.getList(2);
			},
			async changeTab(event) {
				let index = event.detail.current;
				console.log("切换到了第：" + index + "个")
				if (this.isClickChange) {
					this.tabIndex = index;
					this.isClickChange = false;
					return;
				}
				let tabBar = await this.getElSize('tab-bar');
				let tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0;
	
				for (let i = 0; i < index; i++) {
					let result = await this.getElSize(this.tabBars[i].title);
					width += result.width;
				}
				console.log("切换到了：" + this.tabBars[index].id)
				var nowWidth = 0;
				let winWidth = uni.getSystemInfoSync().windowWidth,
					nowElement = await this.getElSize(this.tabBars[index].title);
					console.log("切换到了：" + JSON.stringify(nowElement))
					nowWidth = nowElement.width;
				if (width + nowWidth - tabBarScrollLeft > winWidth) {
					this.scrollLeft = width + nowWidth - winWidth;
				}
				if (width < tabBarScrollLeft) {
					this.scrollLeft = width;
				}
				
				this.isClickChange = false;
				
				
				this.tabIndex = this.tabBars[index].id;
	
				// 首次切换后加载数据
				this.currentList = this.newsList[index] ? this.newsList[index].data : [];
				
				const activeTab = this.newsList[this.tabIndex];
				if (!activeTab || activeTab.data.length === 0) {
					this.getList();
				}
			},
			getNodeSize(node) {
				return new Promise((resolve, reject) => {
					dom.getComponentRect(node, (result) => {
						resolve(result.size);
					});
				});
			},
			onRefresh(event) {
				this.refreshText = '正在刷新...';
				this.refreshing = true;
				this.getList();
			},
			getElSize(id) { //得到元素的size
				return new Promise((res, rej) => {
					uni.createSelectorQuery().select('#' + id).fields({
						size: true,
						scrollOffset: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
			async tapTab(tab) { //点击tab-bar
				var index = tab.id;
				this.currentList = this.newsList[index] ? this.newsList[index].data : [];
				console.log("切换到了：" + tab.name)
				if (this.tabIndex === index) {
					console.log("切换到了：未成功")
					return false;
				} else {
					let tabBar = await this.getElSize('tab-bar'),
						tabBarScrollLeft = tabBar.scrollLeft; //点击的时候记录并设置scrollLeft
					this.scrollLeft = tabBarScrollLeft;
					this.isClickChange = true;
					this.tabIndex = index;
					// 首次切换后加载数据
					const activeTab = this.newsList[this.tabIndex];
					if (!activeTab || activeTab.data.length === 0) {
						this.getList();
					}
				}
			},
			loadImg() {
				console.log("loadImg");
				var that = this;
				uni.createSelectorQuery().selectAll('.lazy').boundingClientRect((images) => {
					images.forEach((image, index) => {
						if (image.top <= that.windowHeight) {
							that.currentList[image.dataset.index].show = true;
						}
					})
				}).exec()
			},
			imgOnLoad(e) {
				console.log("imgOnLoad");
				this.currentList[e.target.dataset.index].loaded = true
			}
		}
	}
</script>

<style lang="scss">
	@import url("../../static/css/bukaa-font.css");
	@import url("../../static/css/list.css");
	.user-info{
		width: 94%;
	    zoom: 1;
		margin: auto;
		margin-top: 30upx;
		.base-info{
			text-align: center;
			margin-bottom: 24upx;
			.avatar{
				width: 240upx;
				height: 240upx;
				margin-bottom: 20upx;
				border-radius: 50%;
			}
			.username{
				font-size: 40upx;
				line-height: 56upx;
				font-weight: 500;
				color: rgba(0,0,0,.85);
				margin-bottom: 8upx;
			}
			.sign{
				font-family: Chinese Quote,-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol;
				font-size: 28upx;
				font-variant: tabular-nums;
				line-height: 1.6;
				color: rgba(0,0,0,.65);
			}
		}
		.other-info{
			font-size: 28upx;
			line-height: 1.5;
			color: rgba(0,0,0,.65);
			i{
				display: inline;
			}
			text{
				margin-left: 10upx
			}
		}
		.dashed{
			background: none;
			border-top: 1px dashed #e8e8e8;
			display: block;
			height: 1px;
			width: 100%;
			min-width: 100%;
			margin: 20upx 0;
			clear: both;
		}
		.tags{
			box-sizing: border-box;
			font-family: Chinese Quote,-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol;
			font-size: 24upx;
			font-variant: tabular-nums;
			line-height: 1.5;
			color: rgba(0,0,0,.65);
			.tagTitle{
				font-weight: 500;
				color: rgba(0,0,0,.85);
				margin-bottom: 24upx;
			}
			.tag{
				margin: 5upx 10upx 5upx 0;
				color: rgba(0,0,0,.65);
				font-variant: tabular-nums;
				line-height: 1.5;
				box-sizing: border-box;
				list-style: none;
				display: inline-block;
				line-height: 40upx;
				height: 44upx;
				padding: 0 14upx;
				border-radius: 8upx;
				border: 1px solid #d9d9d9;
				background: #fafafa;
				font-size: 24upx;
				transition: all .3s cubic-bezier(.215,.61,.355,1);
				opacity: 1;
				cursor: pointer;
				white-space: nowrap;
			}
		}
		.categories{
			font-family: Chinese Quote,-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol;
			font-size: 28upx;
			font-variant: tabular-nums;
			line-height: 1.5;
			color: rgba(0,0,0,.65);
			.catTitle{
				font-weight: 500;
				color: rgba(0,0,0,.85);
				margin-bottom: 24upx;
			}
			.container{
				position: relative;
				transition: opacity .3s;
				zoom: 1;
				.row{
					position: relative;
					height: auto;
					zoom: 1;
					display: block;
					box-sizing: border-box;
					display: inline-flex;
					width: 33.3%;
					.ico{
						margin-right: 24upx;
						width: 48upx;
						height: 48upx;
						line-height: 48upx;
						border-radius: 50%;
						font-size: 28upx;
						font-variant: tabular-nums;
						box-sizing: border-box;
						margin: 0;
						padding: 0;
						list-style: none;
						display: inline-block;
						text-align: center;
						background: transparent;
						color: #fff;
						white-space: nowrap;
						position: relative;
						overflow: hidden;
						vertical-align: middle;
					}
					.cat{
						display: block;
						color: rgba(0,0,0,.65);
						transition: color .3s;
						overflow: hidden;
						text-overflow: ellipsis;
						word-break: break-all;
						white-space: nowrap;
						line-height: 48upx;
						margin-left: 10upx;
					}
				}
			}
		}
		.postListTitle{
			font-weight: 500;
			color: rgba(0,0,0,.85);
			margin-bottom: 24upx;
		}
	}
</style>
